package crypto;

import java.security.*;

public class generateRSAkey {

    public static void main(String[] args) {
        try {
            SecureRandom sr = new SecureRandom();
            KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA",
                    new org.bouncycastle.jce.provider.BouncyCastleProvider());
            // 注意密钥大小1024
            kg.initialize(1024, sr);
            KeyPair keyPair = kg.generateKeyPair();
            PrivateKey priKey = keyPair.getPrivate();
            PublicKey pubKey = keyPair.getPublic();
            byte[] publicKey = pubKey.getEncoded();
            byte[] privateKey = priKey.getEncoded();
            System.out.println("公钥：" + pubKey.getFormat() + " ; "
                    + byteArr2HexString(publicKey));
            System.out.println("私钥：" + priKey.getFormat() + " ; "
                    + byteArr2HexString(privateKey));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static String byteArr2HexString(byte[] bytearr) {
        if (bytearr == null) {
            return "null";
        }
        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < bytearr.length; k++) {
            if ((bytearr[k] & 0xFF) < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(bytearr[k] & 0xFF, 16));
        }
        return sb.toString();
    }

}
